package com.zero.manage.web.utils;

import cn.hutool.core.util.StrUtil;
import com.zero.manage.web.components.dao.SysPowerDao;
import com.zero.manage.web.config.shiro.MyAuthorizationFilter;
import io.gitee.zerowsh.enums.ToolEnums;
import com.zero.manage.web.jwt.JwtFilter;
import lombok.extern.log4j.Log4j2;
import org.apache.shiro.spring.web.ShiroFilterFactoryBean;

import javax.servlet.Filter;
import java.util.*;


/**
 * 服务工具类
 *
 * @author zero
 */
@Log4j2
public class CommonUtils {
    public static Map<String, String> handleShiroPower(ShiroFilterFactoryBean shiroFilterFactoryBean, SysPowerDao sysPowerDao) {
//        shiroFilterFactoryBean.setLoginUrl("/unLogin");//没登录跳转接口
//        shiroFilterFactoryBean.setSuccessUrl("/index");//登录成功后跳转的连接
//        shiroFilterFactoryBean.setUnauthorizedUrl("/noPermission"); //未授权跳转页面
        // 添加自己的过滤器并且取名为jwt
        Map<String, Filter> filterMap = new HashMap<>(2);
        filterMap.put("jwt", new JwtFilter());
        filterMap.put("perms", new MyAuthorizationFilter());
        shiroFilterFactoryBean.setFilters(filterMap);
        //拦截器
        Map<String, String> map = new LinkedHashMap<>();
        /*
         * 过滤链定义，从上向下顺序执行，/**放在最下面，过滤链的最后一关，表示除去以上各环节，剩余url的都需要验证
         * authc:所有url都必须认证通过才可以访问; anon:所有url都都可以匿名访问
         */
        /*
         * 登录、重置密码、注册接口、验证码可以匿名访问
         */
        map.put("/sysUser/sysLogout", "anon");
        map.put("/sysUser/sysLogin", "anon");
        map.put("/sysUser/captcha", "anon");
        /*
         * 配合前端实现动态路由
         */
        map.put("/sysUser/initFrontEndInfo", "anon");
        /*
         * swagger相关
         */
        map.put("/doc.html", "anon");
        map.put("/swagger-resources/**", "anon");
        map.put("/v2/api-docs", "anon");
        map.put("/v2/api-docs-ext", "anon");
        map.put("/webjars/**", "anon");
        /*
         * 连接池相关
         */
        map.put("/druid/**", "anon");
        //自定义加载权限资源关系
        List<String> sysPowerUrlArray = sysPowerDao.getUrlByType(ToolEnums.PowerTypeEnums.POWER);
        if (!sysPowerUrlArray.isEmpty()) {
            for (String resources : sysPowerUrlArray) {
                if (StrUtil.isNotBlank(resources)) {
                    String permission = "perms[" + resources + "]";
                    map.put(resources, "jwt," + permission);
                }
            }
        }
        //其他接口必须登录才能访问
        map.put("/**", "jwt");
        return map;
    }

    /**
     * obj转str
     *
     * @param obj
     * @return
     */
    public static String handleObjTurnStr(Object obj) {
        return Objects.isNull(obj) ? "" : obj.toString();
    }

}
